#import <appkit/Application.h>
#import <appkit/appkit.h>
#import <sys/file.h>
#import <stdio.h>
#import <stdlib.h>
#import <string.h>
#import "ToyWinPPM.h"
#import "ppm.h"
#import "strfunc.h"


static FILE *openPipe(const char **list)
{
	int pfd[2];

	if (list == NULL || access(list[0], X_OK) < 0)
		return NULL;	/* not executable */
	(void)pipe(pfd);
	if (fork() == 0) { /* child process */
		(void)close(1);
		dup(pfd[1]);
		(void)close(pfd[0]);
		(void)close(pfd[1]);
		execv(list[0], &list[1]);
		exit(1);	/* Error */
	}
	(void)close(pfd[1]);
	return fdopen(pfd[0], "r");
}


@implementation ToyWinPPM

- (int)drawToyWin:(const char *)fileName Type:(int)type Num:(int)num
{
	FILE *fp = NULL;
	commonInfo *cinf = NULL;
	int err = 0;
	const char *ext = NULL;
	unsigned char *map[5];

	if (type == Type_ppm)
		fp = fopen(fileName, "r");
	else {
		fp = openPipe(execList);
		ext = (extension && *extension) ? extension : execList[1];
		free((void *)execList);
		execList = NULL;
	}
	if (fp == NULL)
		return Err_OPEN;

	if ((cinf = loadPpmHeader(fp, &err)) == NULL) {
		(void)fclose(fp);
		return err;
	}

	[self initLocateWindow:fileName
		Width:cinf->width Height:cinf->height Num:num];

/* Bitmap data of planes in 'map[]' is one block of memory area.
   map[0] is beginning of the area, and map[1] = map[0] + (size of plane),
   and so on. But, if the image is monochrome, map[1] is NULL.
   The area of map[0] and (commonInfo *)cinf are kept in an object of
   ToyView, and freed by it.
*/
	err = ppmGetImage(fp, cinf, map, ext);
	(void)fclose(fp);
	if (err) /* 警告のみ */
		errAlert(fileName, err);

	if ([self drawView:map info: cinf] == nil)
		return -1;

	return 0;
}

- setExecList: (char **)list ext: (const char *)type
	/* list is free-ed by this obj */
{
	execList = list;
	extension = type;
	return self;
}

@end
